package thread;

/**
 * 演示Wait/notify的使用
 */
public class WaitDemo {

    Object food = null;

    /**
     * 正常情况
     * @throws InterruptedException
     */
    void normal() throws InterruptedException {
        Thread thread = new Thread(() -> {
            synchronized (this) {
                while (food == null) {
                    System.out.println("没有包子，等待");
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("买到包子，回家");
        });
        thread.start();
        Thread.sleep(1000);
        food = new Object();
        synchronized (this) {
            System.out.println("生产了包子，通知");
            this.notify();
        }
    }

    /**
     * 错过通知，死锁
     * @throws InterruptedException
     */
    void missNotify() throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (food == null) {
                try {
                    Thread.sleep(1000);
                    System.out.println("没有包子，等待");
                    synchronized (this) {
                        this.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("买到包子，回家");
        });
        thread.start();
        Thread.sleep(200);
        food = new Object();
        synchronized (this) {
            System.out.println("生产了包子，通知");
            this.notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitDemo d = new WaitDemo();
//        d.normal();
        d.missNotify();
    }
}
